import 'package:cbec_app/components/base/base_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_popup/flutter_popup.dart';

import '../../../components/decoration/decoration_rich_text_parse.dart';
import '../../../entity/lottery/lottery_bean.dart';
import '../../../entity/lottery/lottery_list_bean.dart';
import '../../../utils/Tools.dart';
import 'SimpleLotteryValue.dart';

class SimpleLotteryWidget extends StatefulWidget {
  final SimpleLotteryController controller;
  final LotteryBean? info;
  final LotteryListBean? lotteryListBean;
  final Function? onPress;
  final Function? onPressList;

  ///富文本配置
  final Map<String, dynamic> mapParam;

  SimpleLotteryWidget(
      {Key? key,
      required this.controller,
      this.info,
      this.lotteryListBean,
      this.onPress,
      this.onPressList,
      required this.mapParam});

  @override
  _SimpleLotteryWidgetState createState() => _SimpleLotteryWidgetState();
}

class _SimpleLotteryWidgetState extends State<SimpleLotteryWidget>
    with TickerProviderStateMixin {
  late Animation<int> _selectedIndexTween;
  late AnimationController _startAnimateController;
  int _currentSelect = -1;
  final int _totalIndex = 8;

  late VoidCallback _listener;
  bool _continueToTarget = false;
  late List<String> _rewardsList;

  late TabController tabCtr;

  /// 选中下标的映射
  // final Map<int, int> _selectIndexMap = const {
  //   0: 0,
  //   1: 3,
  //   2: 6,
  //   3: 7,
  //   4: 8,
  //   5: 5,
  //   6: 2,
  //   7: 1
  // };
  /// 选中下标的映射
  final Map<int, int> _selectIndexMap = const {
    0: 0,
    1: 1,
    2: 2,
    3: 5,
    4: 8,
    5: 7,
    6: 6,
    7: 3
  };

  /// 正向
  final Map<int, int> _reverseSelectMap = const {
    0: 0,
    1: 1,
    2: 2,
    5: 3,
    8: 4,
    7: 5,
    6: 6,
    3: 7
  };

  /// 反向map
  // final Map<int, int> _reverseSelectMap = const {
  //   0: 0,
  //   3: 1,
  //   6: 2,
  //   7: 3,
  //   8: 4,
  //   5: 5,
  //   2: 6,
  //   1: 7
  // };

  _SimpleLotteryWidgetState() {
    _listener = () {
      _continueToTarget = false;
      // 开启抽奖动画
      if (widget.controller.value.isPlaying) {
        // 如果是假的，则只是循环抽奖过程
        if (widget.controller.value.isFake) {
          _startFakeAnimation();
        } // 如果在假装抽奖的过程中，设置了target
        else if (widget.controller.value.isSetTargetDuringFake) {
          setState(() {
            _continueToTarget = true;
          });
        } // 常规的直接抽奖
        else {
          _startActualAnimation();
        }
      }
    };
  }

  /// 初始化tween
  ///
  /// [target] 中奖的目标
  Animation<int> _initSelectIndexTween(
          {int begin = 0, int end = 0, Curve curve = Curves.linear}) =>
      StepTween(begin: begin, end: end).animate(
          CurvedAnimation(parent: _startAnimateController, curve: curve));

  _startFakeAnimation() {
    _selectedIndexTween = _initSelectIndexTween(end: _totalIndex);
    _startAnimateController
      ..reset()
      ..duration = widget.controller.value.singleRoundFakeDuration
      ..repeat();
  }

  _startActualAnimation() {
    _selectedIndexTween = _initSelectIndexTween(
        end: widget.controller.value.repeatRound * _totalIndex +
            widget.controller.value.target,
        curve: Curves.easeOutCubic);
    _startAnimateController
      ..reset()
      ..duration = widget.controller.value.duration
      ..forward();
  }

  @override
  void didUpdateWidget(covariant SimpleLotteryWidget oldWidget) {
    if (oldWidget.controller != widget.controller) {
      _reset(oldWidget);
    }
    super.didUpdateWidget(oldWidget);
  }

  _reset(SimpleLotteryWidget oldWidget) {
    oldWidget.controller.removeListener(_listener);
    widget.controller.addListener(_listener);
    _rewardsList = widget.controller.value.rewardsList;
    _currentSelect = -1;
  }

  @override
  void initState() {
    tabCtr = TabController(length: 2, vsync: this);

    _startAnimateController = AnimationController(
        vsync: this, duration: widget.controller.value.duration);
    _selectedIndexTween = _initSelectIndexTween(end: _totalIndex);

    // 动画监听
    _startAnimateController.addListener(() {
      // 更新选中的下标
      _currentSelect =
          _selectIndexMap[_selectedIndexTween.value % _totalIndex]!;

      // 在假的抽奖过程到0位置时, 开启真的抽奖, 主要是起到无缝衔接
      if (_continueToTarget && _currentSelect == 0) {
        _continueToTarget = false;
        _startActualAnimation();
      }
      if (_startAnimateController.isCompleted) {
        widget.controller.finish();
        Future.delayed(const Duration(seconds: 3),
            () => {_currentSelect = -1, setState(() {})});
      }
      setState(() {});
    });

    // 控制监听
    widget.controller.addListener(_listener);
    _rewardsList = widget.controller.value.rewardsList;
    super.initState();

    bgColor = widget.mapParam['bg_color'];
    bgColor2 = widget.mapParam['bg_color2'];
    prizeColor = widget.mapParam['prize_color'];
    prizeColor = widget.mapParam['prize_color'];
    btnTextColor = widget.mapParam['btn_text_color'];
    btnColor = widget.mapParam['btn_color'];
    bdr = widget.mapParam['bdr'] * 1.0;
    marginTop = widget.mapParam['page_margin_top'] * 1.0;
    marginBottom = widget.mapParam['page_margin_top'] * 1.0;

    // animationColor = Tools.fromHex('rgba(252,255,9,0.5)');
  }

  String bgColor = '#FC6561';
  String bgColor2 = '#80142A';
  String prizeColor = '#FFF4D1';
  String btnTextColor = '#FFE6B6';
  String btnColor = '#FC6561';
  Color animationColor = Colors.blue.withOpacity(0.5);
  double bdr = 8;
  double marginTop = 0;
  double marginBottom = 0;

  @override
  void deactivate() {
    widget.controller.removeListener(_listener);
    super.deactivate();
  }

  @override
  void dispose() {
    _startAnimateController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(top: marginTop, bottom: marginBottom),
        child: Column(
          children: [
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                child: Text(
                  '剩余抽奖次数：${widget.info?.num ?? 0}',
                  style: TextStyle(
                      color: Tools.fromHex('#F83F2D'),
                      fontWeight: FontWeight.w400,
                      fontSize: 14),
                ),
              ),
            ),
            Container(
              width: Screen.width - 36,
              height: Screen.width - 36,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Tools.fromHex(bgColor), // 背景颜色
                borderRadius: BorderRadius.circular(bdr), // 设置圆角
              ),
              child: Container(
                margin: EdgeInsets.all(15),
                padding: EdgeInsets.all(10),
                alignment: Alignment.center,
                // color: Colors.red,
                decoration: BoxDecoration(
                  color: Tools.fromHex(bgColor2), // 背景颜色
                  borderRadius: BorderRadius.circular(bdr), // 设置圆角
                ),
                child: GridView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    padding: EdgeInsets.zero,
                    itemCount: 9,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 4,
                        mainAxisSpacing: 4),
                    itemBuilder: (context, index) {
                      if (index != 4) {
                        return LayoutBuilder(builder: (context, containers) {
                          return Container(
                            child: Stack(
                              alignment: Alignment.center,
                              children: <Widget>[
                                Container(
                                  // width:(MediaQuery.of(context).size.width-95)/3,
                                  // height:(MediaQuery.of(context).size.width-44)/3,
                                  width: containers.biggest.width - 5,
                                  height: containers.biggest.width - 5,
                                  decoration: BoxDecoration(
                                    color: Tools.fromHex(prizeColor), // 背景颜色
                                    borderRadius:
                                        BorderRadius.circular(bdr), // 设置圆角
                                  ),
                                  child: _rewardsList.isEmpty
                                      ? Image.asset(
                                          "assets/images/ic_lottery_default.png")
                                      : BaseImage(
                                          url: _rewardsList[
                                              _reverseSelectMap[index]!],
                                          width: 50,
                                          height: 50,
                                          borderRadius:
                                              BorderRadius.circular(bdr),
                                        ),
                                ),
                                Container(
                                    // color: index == _currentSelect
                                    //     ? Colors.blue.withOpacity(0.5)
                                    //     : Colors.amber.withOpacity(0.5),
                                    decoration: index == _currentSelect
                                        ? BoxDecoration(
                                            color: animationColor,
                                            // 背景颜色
                                            borderRadius: BorderRadius.circular(
                                                bdr), // 设置圆角
                                          )
                                        : BoxDecoration(
                                            color:
                                                Colors.amber.withOpacity(0.0),
                                            // 背景颜色
                                            borderRadius: BorderRadius.circular(
                                                bdr), // 设置圆角
                                          )),
                              ],
                            ),
                          );
                        });
                      }
                      return GestureDetector(
                        onTap: () {
                          widget.onPress?.call();
                        },
                        child: Container(
                          alignment: Alignment.center,
                          child: Text(
                            '点击\n抽奖',
                            style: TextStyle(
                                color: Tools.fromHex(btnTextColor),
                                fontSize: 20,
                                fontWeight: FontWeight.w400),
                          ),
                          decoration: BoxDecoration(
                            color: Tools.fromHex(btnColor), // 背景颜色
                            borderRadius: BorderRadius.circular(bdr), // 设置圆角
                          ),
                        ),
                      );
                    }),
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                GestureDetector(
                  onTap: () {
                    _showRuleDialog();
                  },
                  child: Card(
                    child: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                      child: Text(
                        '活动规则',
                        style: TextStyle(
                            color: Tools.fromHex('#F83F2D'),
                            fontWeight: FontWeight.w400,
                            fontSize: 14),
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    widget.onPressList?.call();
                  },
                  child: Card(
                    child: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                      child: Text(
                        '我的奖品',
                        style: TextStyle(
                            color: Tools.fromHex('#F83F2D'),
                            fontWeight: FontWeight.w400,
                            fontSize: 14),
                      ),
                    ),
                  ),
                ),
              ],
            )
          ],
        ));
  }

  void _showRuleDialog() {
    showDialog(
        context: context,
        builder: (c) {
          Map<String, dynamic> param = Map();
          param['color'] = '#ffffff';
          param['content'] = widget.info?.content ?? "";
          return Dialog(
            backgroundColor: Colors.transparent,
            child: Container(
              height: 250,
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.all(6),
                    width: MediaQuery.of(context).size.width,
                    height: 200,
                    decoration: BoxDecoration(
                      color: Tools.fromHex('#FFFFFF'), // 背景颜色
                      borderRadius: BorderRadius.circular(8), // 设置圆角
                    ),
                    child: DecorationRichTextParse(info: param),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(c);
                    },
                    child: Image.asset(
                      "assets/images/close.png",
                      color: Colors.white,
                    ),
                  )
                ],
              ),
            ),
          );
        });
  }
}
